package com.smartmail.receiving.imap;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.UIDFolder;
import javax.mail.internet.MimeMessage;

import android.util.Log;

import com.smartmail.Attachment;
import com.smartmail.accounts.MailAccount;
import com.smartmail.mailing.MailMessage;
import com.smartmail.mime.MimeParser;
import com.smartmail.utility.MessageUtility;

/**
 * Class used to extract the messages stored on the IMAP server attachments.
 * 
 * @author Tomek
 *
 */
public class IMAPAttachmentCatcher {
	
	
	/**
	 * This method attempts to connect to the imap server and extract from it the message.
	 * Then from this message are extracted attachments.
	 * 
	 * @param _mailMessage - MailMessage object which identifies message
	 * @param _mailAccount - MailAccount object which identifies mailbox in with message exists.
	 * @return - list of attachments extracted from message.
	 */
	public List<Attachment> getIMAPAttachments(MailMessage _mailMessage, MailAccount _mailAccount) {
		
		closeConnections();
		
		/**
		 * connect to the store and obtain inbox folder
		 */
		List<Attachment> attachments = new LinkedList<Attachment>();
		
		try{
			Properties props = new Properties();
			
			//set connection timeout to 5 secods
			props.put("mail.imap.timeout", 5000);
			props.put("mail.imaps.timeout", 5000);
			
			props.putAll(_mailAccount.getAccountProperties());
	
			Session session = Session.getInstance(props,
					_mailAccount.getPasswordAuthentication());
			
			_store = session.getStore();
	
			_store.connect(_mailAccount.getIncomingMailServerAddress(),
					_mailAccount.getAccountUsername(),
					_mailAccount.getAccountPassword());
	
			_folder = _store.getDefaultFolder();
			_folder = _store.getFolder("INBOX");
			_folder.open(Folder.READ_WRITE);
			
			Message messages[] = _folder.getMessages();
			//initial identificators downloading
			FetchProfile fp = new FetchProfile();
			fp.add( UIDFolder.FetchProfileItem.UID );
			_folder.fetch( messages, fp );
			com.sun.mail.imap.IMAPFolder imapFolder = (com.sun.mail.imap.IMAPFolder)_folder;
			
			long uid;
			try{
				uid = Long.parseLong(_mailMessage.getMessageUID());
			} catch (NumberFormatException ex){
				
				Log.d(_logTag, "IMAPAttachmentCatcher: getIMAPAttachments - number format exception");
				return null;
			}
			
			
			MimeMessage message = (MimeMessage)imapFolder.getMessageByUID(uid);
			
			// check message hash
			if( !MessageUtility.getHash(message).equals(_mailMessage.getMessageHash()))
				return null;
			
			MimeParser.getAllAttachments(message, attachments);
			
		} catch(MessagingException ex){
			
			Log.d(_logTag, "IMAPAttachmentCatcher: getIMAPAttachments - messaging exception");
			Log.d(_logTag, "IMAPAttachmentCatcher: getIMAPAttachments " + ex.getMessage() + " " + ex.toString());
			
			
			return null;
		} 
		
		
		return attachments;
	}
	
	/**
	 * Close connections with Folder and Store
	 */
	public void closeConnections(){
		
		try{
		if(_folder != null)
			_folder.close(false);
		if(_store != null)
			_store.close();
		
		} catch(MessagingException me){
			
			Log.d(_logTag, "IMAPAttachmentCatcher : closeConnections - messaging exception");
		}
	}
	
	/**
	 * log tag for logging purposes
	 */
	private static String _logTag = "com.smartmail.receiving.imap";
	
	/**
	 * IMAPFolder object
	 */
	private Folder _folder;
	
	/**
	 * Store object
	 */
	private Store _store;

}
